package com.yearEndWorkload.listen;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.yearEndWorkload.pojo.entity.WorkloadLoad;
import com.yearEndWorkload.pojo.excel.importTemplate.WorkloadImportExcel;
import com.yearEndWorkload.pojo.form.add.AddWorkloadLoadForm;
import com.yearEndWorkload.service.WorkloadLoadService;

import java.util.List;

public class WordloadLoadListener implements ReadListener<WorkloadImportExcel> {
    private static final int BATCH_COUNT = 100;
    private WorkloadLoadService workloadLoadService;
    /**
     * 缓存的数据
     */
    private List<WorkloadLoad> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    public WordloadLoadListener(WorkloadLoadService workloadLoadService) {
        this.workloadLoadService = workloadLoadService;
    }

    @Override
    public void invoke(WorkloadImportExcel workloadImportExcel, AnalysisContext analysisContext) {
        WorkloadLoad workloadLoad = new WorkloadLoad();
        workloadLoad.setYear(workloadImportExcel.getYear());
        workloadLoad.setWorkloadType(workloadImportExcel.getWorkloadType());
        workloadLoad.setWorkloadName(workloadImportExcel.getWorkloadName());
        workloadLoad.setTeacherName(workloadImportExcel.getTeacherName());
        workloadLoad.setAmount(workloadImportExcel.getAmount());
        workloadLoad.setNumber(workloadImportExcel.getNumber());
        workloadLoad.setReporter(workloadImportExcel.getReporter());
        cachedDataList.add(workloadLoad);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    private void saveData() {
        workloadLoadService.saveOrUpdateBatch(cachedDataList);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }
}
